/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-04-26 13:43:27
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-07-21 14:24:53
 * @FilePath: \ken147258.topayClient\src\store\modules\app.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// import { constantRoutes } from "@/router";
import { store, useUserStore, usePermissionStore } from "@/store";
import { all } from "@/api/other/pay_product";
import { payProductList } from "@/api/payee/payProduct";
import { merchanPayProductList } from "@/api/payer/payProduct";

import { status as statusByOther } from "@/api/other/order";
import { status as statusByPayer } from "@/api/payer/order";

import router from "@/router";

const Layout = () => import("@/layout/index.vue");

// setup
export const usePayProductStore = defineStore("pay_product", () => {
  const userStore = useUserStore();
  const products = useStorage(userStore.getLoginType() + 'pay_product', {
    list: [],
    actualList: [],
    dictionary: {},
  });

  function loadPayProducts() {
    return new Promise<any[]>(async (resolve) => {
      const loginType = userStore.getLoginType();

      if (!products.value.list?.length) {

        let func = all;

        if (loginType === 'other') {

        } else if (loginType === 'payee') {
          func = payProductList;
        } else if (loginType === 'payer') {
          func = merchanPayProductList;
        }

        products.value.list = await func();

        if (!products.value.list.length) {
          products.value.list = products.value.list.list;
        }
      }
      const routerAppendArr = products.value.actualList = getRoutes(products.value.list);

      if (loginType === 'other') {
        const accessRoutes1 = await usePermissionStore().generateRoutesAppend(routerAppendArr[0], 'channel-management');

        accessRoutes1.map((route: RouteRecordRaw) => {
          router.addRoute('channel-management', route);
        });

        // const accessRoutes2 = await usePermissionStore().generateRoutesAppend(routerAppendArr[1], 'channel-order');

        // accessRoutes2.map((route: RouteRecordRaw) => {
        //   router.addRoute('channel-order', route);
        // });
      }

      resolve(products.value.list || []);
    })
  }

  function loadStatus() {
    return new Promise<object>(async (resolve) => {
      if (!Object.keys(products.value.dictionary).length) {

        const loginType = useUserStore().getLoginType();
        let func = null;

        if (loginType === 'other') {
          func = statusByOther;
        } else if (loginType === 'payee') {

        } else if (loginType === 'payer') {
          func = statusByPayer;
        }

        if (func) {
          const dictionary = await func();

          products.value.dictionary = {
            status: Object.keys(dictionary.order_status).map(item => ({
              label: dictionary.order_status[item],
              value: item.toString(),
            })),
            payment_status: Object.keys(dictionary.payment_order_status).map(item => ({
              label: dictionary.payment_order_status[item],
              value: item.toString(),
            })),
          };
        }
      }

      resolve(products.value.dictionary);
    })
  }

  function refreshAddedRoute() {
    const len = router.getRoutes().filter(item => {
      return ['channel-management', 'channel-order'].some(name => item.name && item.name.indexOf(name) === 0);
    }).length;

    if (len > 4) {
      products.value.actualList.map(list => {
        list.map(item => {
          router.removeRoute(item.name);
        });
      });
      products.value.list = [];
      products.value.actualList = [];

      loadPayProducts();
    }
  }

  function getRoutes(res) {
    let result = [];

    if (res && res.length) {

      const loginType = useUserStore().getLoginType();

      result[0] = res.map((item: any) => {
        return {
          path: "/" + loginType + "/channel-management/management/" + item.pass_code,
          component: loginType + "/channel-management/management",
          name: "channel-management-" + item.pass_code,
          meta: {
            title: item.pro_name,
            hidden: false,
            keepAlive: true,
            page: 'channel',
            ...item,
          },
        };
      });

      result[1] = res.map((item: any) => {
        return {
          path: "/" + loginType + "/channel-order/order/" + item.pass_code,
          component: loginType + "/channel-order/order",
          name: "channel-order-" + item.pass_code,
          meta: {
            title: item.pro_name,
            hidden: false,
            keepAlive: true,
            page: 'order',
            ...item,
          },
        };
      });
    }

    return result;
  }

  function getDictionary() {
    return products.value.dictionary;
  }


  return {
    products,
    loadPayProducts,
    refreshAddedRoute,
    loadStatus,
    getDictionary,
  };
});

// 非setup
export function usePayProductStoreHook() {
  return usePayProductStore(store);
}
